local AddPrefabPostInit = AddPrefabPostInit
GLOBAL.setfenv(1, GLOBAL)

local witch_boundaries = {
    "walpurgisnight_boundary",
    "witch_gisela_boundary",
    "witch_shadow_knight_boundary",
    "witch_deciduoustrees_boundary",
}

local function GetRandomPoint()
    local map_width, map_height = TheWorld.Map:GetSize()
    local x, z
    for i = 1, 10000 do
        x = math.random(-map_width, map_width)
        z = math.random(-map_height, map_height)

        if not TheWorld.Map:IsOceanTileAtPoint(x, 0, z) then
            return x, z
        end
    end

    return x, z
end

local function SpawnLonelyHeart(inst)
    if TheWorld.state.isfullmoon and TheWorld.state.cycles < 13 then
        local multiplayer_portal = TheSim:FindFirstEntityWithTag("multiplayer_portal")
        SpawnPrefab("lonely_heart").Transform:SetPosition(multiplayer_portal.Transform:GetWorldPosition())
    end
end

AddPrefabPostInit("forest", function(inst)
    if not TheWorld.ismastersim then
        return
    end

    inst:DoTaskInTime(1, function()
        if not inst.meta.patcher or not inst.meta.patcher.wn_spawned then
            inst.meta.patcher = inst.meta.patcher or {}
            inst.meta.patcher.wn_spawned = true

            for i, prefab in ipairs(witch_boundaries) do
                local x, z = GetRandomPoint()
                SpawnPrefab(prefab).Transform:SetPosition(x, 0, z)
            end

            for i = 1, 350 do
                local x, z = GetRandomPoint()
                SpawnPrefab("magicalgirl_hunter").Transform:SetPosition(x, 0, z)
            end
        end
    end)

    inst:WatchWorldState("isfullmoon", SpawnLonelyHeart)
end)
